package cn.droidlover.xdroidmvp.imageloader;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.widget.ImageView;

import com.bumptech.glide.DrawableRequestBuilder;
import com.bumptech.glide.DrawableTypeRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.bumptech.glide.request.target.SimpleTarget;

import java.io.File;

import cn.droidlover.xdroidmvp.kit.NLog;
import jp.wasabeef.glide.transformations.BlurTransformation;

/**
 * Created by wanglei on 2016/11/28.
 */

public class GlideLoader implements ILoader {
    Context context;

    @Override
    public void init(Context context) {
        this.context = context;
    }

    @Override
    public void loadNet(ImageView target, String url, Options options) {
        load(getRequestManager(target.getContext()).load(url), target, options,false,false);

    }

    @Override
    public void loadNet(ImageView target, String url, Options options,LoadCallback callback) {
        load(getRequestManager(target.getContext()).load(url), target, options, callback);
    }


    @Override
    public void loadCircleShapeNet(ImageView target, String url, Options options) {
        load(getRequestManager(target.getContext()).load(url), target, options, true, false);
    }

    private void loadNomalNet(Context context, String url, Options options, boolean isCircle, boolean isRound, final LoadCallback callback) {
        DrawableTypeRequest request = getRequestManager(context).load(url);
        if (options == null) options = Options.defaultOptions();

        if (options.loadingResId != Options.RES_NONE) {
            request.placeholder(options.loadingResId);
        }
        if (options.loadErrorResId != Options.RES_NONE) {
            request.error(options.loadErrorResId);
        }

        DrawableRequestBuilder builder = wrapScaleType(request, options)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE);
        if (isCircle) {
            builder.transform(new GlideCircleTransform(context));
        }
        if (isRound) {
            builder.transform(new GlideRoundTransform(context));
        }

        builder.crossFade()
                .thumbnail(0.1f)
                .into(new SimpleTarget<GlideBitmapDrawable>() {
                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        super.onLoadFailed(e, errorDrawable);
                        if (callback != null) {
                            callback.onLoadFailed(e);
                        }
                    }

                    @Override
                    public void onResourceReady(GlideBitmapDrawable resource, GlideAnimation<? super GlideBitmapDrawable> glideAnimation) {
                        if (resource != null && resource.getBitmap() != null) {
                            if (callback != null) {
                                callback.onLoadReady(resource.getBitmap());
                            }
                        }
                    }

                });
    }

    @Override
    public void loadNet(Context context, String url, Options options, final LoadCallback callback) {
        loadNomalNet(context, url, options, false, false, callback);
    }

    @Override
    public void loadResource(ImageView target, int resId, Options options) {
        load(getRequestManager(target.getContext()).load(resId), target, options, false, false);
    }

    @Override
    public void loadAssets(ImageView target, String assetName, Options options) {
        load(getRequestManager(target.getContext()).load("file:///android_asset/" + assetName), target, options, false, false);
    }

    @Override
    public void loadFile(ImageView target, File file, Options options) {
        load(getRequestManager(target.getContext()).load(file), target, options, false, false);
    }

    @Override
    public void loadCircleShapeFile(ImageView target, File file, Options options) {
        load(getRequestManager(target.getContext()).load(file), target, options, true, false);

    }


    @Override
    public void clearMemoryCache(Context context) {
        Glide.get(context).clearMemory();
    }

    @Override
    public void clearDiskCache(Context context) {
        Glide.get(context).clearDiskCache();
    }

    @Override
    public void resume(Context context) {
        getRequestManager(context).resumeRequests();
    }

    @Override
    public void pause(Context context) {
        getRequestManager(context).pauseRequests();
    }

    private RequestManager getRequestManager(Context context) {
        if (context instanceof Activity) {
            return Glide.with((Activity) context);
        }
        return Glide.with(context);
    }

    private void load(DrawableTypeRequest request, ImageView target, Options options, boolean isCircle, boolean isRound) {
        if (options == null) options = Options.defaultOptions();

        if (options.loadingResId != Options.RES_NONE) {
            request.placeholder(options.loadingResId);
        }
        if (options.loadErrorResId != Options.RES_NONE) {
            request.error(options.loadErrorResId);
        }

        DrawableRequestBuilder builder = wrapScaleType(request, options)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE);
        if (isCircle) {
            builder.transform(new GlideCircleTransform(target.getContext()));
        }
        if (isRound) {
            builder.transform(new GlideRoundTransform(target.getContext()));
        }

        builder.crossFade().thumbnail(0.5f).into(new GlideDrawableImageViewTarget(target) {
            @Override
            public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> animation) {
                super.onResourceReady(resource, animation);

            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onStop() {
                super.onStop();
            }
        });
    }

    private void load(DrawableTypeRequest request, ImageView target,Options options ,final LoadCallback callback) {

        DrawableRequestBuilder builder = wrapScaleType(request, options)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE);
        builder.crossFade().thumbnail(0.5f).into(new GlideDrawableImageViewTarget(target) {
            @Override
            public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> animation) {
                super.onResourceReady(resource, animation);
                NLog.e("GlideLoader","onResourceReady");
                if (null != callback) {
                    callback.onLoadReady(null);
                }
            }

            @Override
            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                super.onLoadFailed(e, errorDrawable);
                if (null != callback) {
                    callback.onLoadReady(null);
                }
            }

            @Override
            public void onStart() {
                super.onStart();
                NLog.e("GlideLoader","onStart");
            }

            @Override
            public void onStop() {
                super.onStop();
                NLog.e("GlideLoader","onStop");


            }
        });
    }


    private DrawableTypeRequest wrapScaleType(DrawableTypeRequest request, Options options) {
        if (options != null
                && options.scaleType != null) {
            switch (options.scaleType) {
                case MATRIX:
                    break;

                case FIT_XY:
                    break;

                case FIT_START:
                    break;

                case FIT_END:
                    break;

                case CENTER:
                    break;

                case CENTER_INSIDE:
                    break;

                case FIT_CENTER:
                    request.fitCenter();
                    break;

                case CENTER_CROP:
                    request.centerCrop();
                    break;
            }
        }

        return request;
    }

    @Override
    public void loadBlurTransform(final ImageView target, String url) {
        Glide.with(target.getContext())
                .load(url)
                .dontAnimate()
                // 设置高斯模糊
                .bitmapTransform(new BlurTransformation(target.getContext(), 14, 3))
                .into(target);
    }
}
